package cn.smbms.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.alibaba.fastjson.JSONArray;

import cn.smbms.dao.UserMapper;
import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.RoleService;
import cn.smbms.service.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;

@Controller
@RequestMapping("/user")
public class LoginController extends BaseInitController {
	private Logger logger = Logger.getLogger(LoginController.class);

	@Resource
	private UserService userService;
	@Resource
	private RoleService roleService;

	@RequestMapping("/login.html")
	public String login() {
		logger.debug("login====================");
		return "login.jsp";
	}

	@RequestMapping(value = "dologin.html", method = RequestMethod.POST)
	public String doLogin(@RequestParam String userCode, @RequestParam String userPassword, HttpSession session,
			HttpServletRequest request) {
		logger.debug("成功进入doLogin========");
		User user = userService.login(userCode, userPassword);
		if (user != null && user.getUserPassword().equals(userPassword)) {
			session.setAttribute(Constants.USER_SESSION, user);
			return "redirect:/user/main.html";
		} else {
			session.setAttribute("error", "用户名密码不正确");
			return "redirect:/user/login.html";

		}

	}

	/**
	 * 如果你直接进入了main页面没有进行登录，跳回登录页面 避免直接跳mian.html
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "main.html")
	public String main(HttpSession session) {
		// 看看你是否登录 进行重新登录操作 没有登录不能进行业务操作
		if (session.getAttribute(Constants.USER_SESSION) == null) {
			return "redirect:/user/login.html";
		}
		return "frame.jsp";
	}

	/**
	 * 如果你的账号和密码不正确，返回到登录页面 测试全局异常
	 * 
	 * @param userCode
	 * @param userPassword
	 * @return
	 */
	@RequestMapping(value = "exlogin.html", method = RequestMethod.GET)
	public String exlogin(@RequestParam String userCode, @RequestParam String userPassword) {
		logger.info("exLogin ==============");
		User user = userService.login(userCode, userPassword);
		if (user == null) { // 登录失败
			throw new RuntimeException("用户名或者密码不正确");
		}
		return "redirect:/user/main.html";

	}

	/**
	 * 查询用户列表 为什么RequestMapping没有加入method = post或get请求
	 * 因为用户进入用户列表是get请求，查询传参是post请求，如果没有放置method那么不管是get请求还是post请求都可以进入该方法就可以重用
	 * 
	 * @param model
	 * @param queryUserName
	 * @param queryUserRole
	 * @param pageIndex
	 * @return
	 */
	@RequestMapping(value = "/userlist.html")
	public String getUserList(Model model, @RequestParam(value = "queryname", required = false) String queryUserName,
			@RequestParam(value = "queryUserRole", required = false) String queryUserRole,
			@RequestParam(value = "pageIndex", required = false) String pageIndex) {
		// 查询用户列表

		int _queryUserRole = 0;
		List<User> userList = null;
		// 设置页面容量
		int pageSize = Constants.pageSize;
		// 当前页码
		int currentPageNo = 1;

		if (queryUserName == null) {
			queryUserName = "";
		}
		if (queryUserRole != null && !queryUserRole.equals("")) {
			_queryUserRole = Integer.parseInt(queryUserRole);
		}

		if (pageIndex != null) {
			try {
				currentPageNo = Integer.valueOf(pageIndex);
			} catch (NumberFormatException e) {
				return "redirect:/user/syerror.html";
			}
		}
		// 总数量（表）
		int totalCount = userService.getUserCount(queryUserName, _queryUserRole);
		// 总页数
		PageSupport pages = new PageSupport();
		pages.setCurrentPageNo(currentPageNo);
		pages.setPageSize(pageSize);
		pages.setTotalCount(totalCount);

		int totalPageCount = pages.getTotalPageCount();

		// 控制首页和尾页
		if (currentPageNo < 1) {
			currentPageNo = 1;
		} else if (currentPageNo > totalPageCount) {
			currentPageNo = totalPageCount;
		}
		userList = userService.getUserList(queryUserName, _queryUserRole, currentPageNo, pageSize);
		model.addAttribute("userList", userList);
		List<Role> roleList = null;
		roleList = roleService.getRoleList();
		model.addAttribute("roleList", roleList);
		model.addAttribute("queryUserName", queryUserName);
		model.addAttribute("queryUserRole", queryUserRole);
		model.addAttribute("totalPageCount", totalPageCount);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("currentPageNo", currentPageNo);
		return "userlist.jsp";
	}

	/**
	 * 从列表页面进入新增页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/useradd.html", method = RequestMethod.GET)
	// public String addUser(User user,Model model) { //这里是一种实现方式
	public String addUser(@ModelAttribute("user") User user) {
		return "useradd.jsp";

	}

	/**
	 * 获取添加好的数据，刷新用户列表
	 * 
	 * @param user
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/addsave.html", method = RequestMethod.POST)
	public String addUserSave(User user, Model model, HttpSession session, HttpServletRequest request,
			/*
			 * @RequestParam(value = "a_idPicPath", required = false) MultipartFile[] files
			 */
			@RequestParam(value = "attachs", required = false) MultipartFile[] files) {
		logger.debug("AddSave() 进入添加用户方法============" + user.getBirthday());
		boolean falg = true;
		String idPicPath = ""; // 头像
		String workPicPath = ""; // 证件照
		String errKey = "uploadFileError";
		String prexfix = "";
		// 1.设置服务器的地址
		String servler_path = request.getRealPath(File.separator);
		// 2.设置目标地址
		String path = servler_path.substring(0, servler_path.lastIndexOf("\\")) + File.separator + "image";
		for (int i = 0; i < files.length; i++) {
			MultipartFile attach = files[i];
			if (i == 0) {
				errKey = "uploadFileError";
			} else if (i == 1) {
				errKey = "uploaWpError";
			}
			if (!attach.isEmpty()) {

				// 判断是头像不正确还是证件照格式不对
				// 3.文件名称
				String oldFileName = attach.getOriginalFilename();
				// 4.文件大小
				long size = attach.getSize();
				// 5.文件后缀
				prexfix = oldFileName.substring(oldFileName.lastIndexOf(".") + 1, oldFileName.length());
				System.out.println("path=====" + path + "oldFileName======" + oldFileName + "size====" + size + prexfix
						+ "prexfix");
				int maxSize = 5000000;
				if (size > maxSize) {
//					request.setAttribute(errKey, "文件不能超过500KB");
					session.setAttribute(errKey,  "文件不能超过500KB");
					falg = false;
					return "useradd.jsp";
				} else if (!Arrays.asList("jpg", "png", "gif", "jpeg", "pneg").contains(prexfix)) {
//					request.setAttribute(errKey, "文件必须是jpg、png、gif、jpeg、pneg 这些类型");
					session.setAttribute(errKey, "文件必须是jpg、png、gif、jpeg、pneg 这些类型");
					falg = false;
					return "useradd.jsp";
				}
				// 文件上传
				// 对文件名进行重命名 避免覆盖掉同名文件
				String fileName = UUID.randomUUID().toString().replaceAll("-", "") + oldFileName;
				File targetFile = new File(path, fileName);
				if (!targetFile.exists()) { // 如果在Path这个路径下，没有这个文件就创建一个文件夹
					targetFile.mkdirs(); // 创建文件夹
				}
				// 上传到服务器
				try {
					attach.transferTo(targetFile);
				} catch (IllegalStateException | IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					request.setAttribute(errKey, " * 上传失败 ");
					falg = false;
				}
				String finallPath = UUID.randomUUID().toString().replaceAll("-", "") + "." + prexfix;
				if (i == 0) {
					idPicPath = finallPath;
				}
				if (i == 1) {
					workPicPath = finallPath;
				}
				System.out.println(workPicPath + "workPicPath===========");
			}
		}
		if (falg) {
			user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
			user.setCreationDate(new Date());
			user.setIdPicPath(idPicPath);
			user.setWorkPicPath(workPicPath);
			if (userService.add(user)) {
				return "redirect:/user/userlist.html";
			} else {
				return "useradd.jsp";
			}
		}

		return "error.jsp";

	}

	/**
	 * 根据用户id获取用户信息
	 * 
	 * @param uid
	 *            获取到的用户id
	 * @param model保存进模型数据中
	 * @return
	 */
	@RequestMapping(value = "/usermodify.html/{id}", method = RequestMethod.GET)
	public String modifyUser(@PathVariable String id, Model model) {
		User user = userService.getUserById(id);
		model.addAttribute("user", user);
		return "usermodify.jsp";

	}

	/**
	 * 修改用户的保存方法
	 * 
	 * @param user
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/userModifySave", method = RequestMethod.POST)
	public String modifysave(User user, Model model, HttpSession session, HttpServletRequest request,
			@RequestParam(value = "attachs", required = false) MultipartFile[] files) {
		logger.debug("modifysave 进入修改用户方法============" + user.getBirthday());
		boolean falg = true;
		String idPicPath = ""; // 头像
		String workPicPath = ""; // 证件照
		String errKey = "uploadFileError";
		String prexfix = "";
		// 1.设置服务器的地址
		String servler_path = request.getRealPath(File.separator);
		// 2.设置目标地址
		String path = servler_path.substring(0, servler_path.lastIndexOf("\\")) + File.separator + "image";
		for (int i = 0; i < files.length; i++) {
			MultipartFile attach = files[i];
			if (i == 0) {
				errKey = "uploadFileError";
			} else if (i == 1) {
				errKey = "uploaWpError";
			}
			if (!attach.isEmpty()) {

				// 判断是头像不正确还是证件照格式不对
				// 3.文件名称
				String oldFileName = attach.getOriginalFilename();
				// 4.文件大小
				long size = attach.getSize();
				// 5.文件后缀
				prexfix = oldFileName.substring(oldFileName.lastIndexOf(".") + 1, oldFileName.length());
				System.out.println("path=====" + path + "oldFileName======" + oldFileName + "size====" + size + prexfix
						+ "prexfix");
				int maxSize = 5000000;
				if (size > maxSize) {
					request.setAttribute(errKey, "文件不能超过500KB");
					falg = false;
					return "useradd.jsp";
				} else if (!Arrays.asList("jpg", "png", "gif", "jpeg", "pneg").contains(prexfix)) {
					request.setAttribute(errKey, "文件必须是jpg、png、gif、jpeg、pneg 这些类型");
					falg = false;
					return "useradd.jsp";
				}
				// 文件上传
				// 对文件名进行重命名 避免覆盖掉同名文件
				String fileName = UUID.randomUUID().toString().replaceAll("-", "") + oldFileName;
				File targetFile = new File(path, fileName);
				if (!targetFile.exists()) { // 如果在Path这个路径下，没有这个文件就创建一个文件夹
					targetFile.mkdirs(); // 创建文件夹
				}
				// 上传到服务器
				try {
					attach.transferTo(targetFile);
				} catch (IllegalStateException | IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					request.setAttribute(errKey, " * 上传失败 ");
					falg = false;
				}
				String finallPath = UUID.randomUUID().toString().replaceAll("-", "") + "." + prexfix;
				if (i == 0) {
					idPicPath = finallPath;
				}
				if (i == 1) {
					workPicPath = finallPath;
				}
				System.out.println(workPicPath + "workPicPath===========");
			}
		}
		if (falg) {
			user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
			user.setCreationDate(new Date());
			user.setIdPicPath(idPicPath);
			user.setWorkPicPath(workPicPath);
			if (userService.modify(user)) {
				return "redirect:/user/userlist.html";
			} else {
				return "usermodify.jsp";
			}
		}

		return "error.jsp";

	}

 

	/**
	 * 查询用户名是否重复
	 * 
	 * @return
	 */
	@RequestMapping("/userCodeExit")
	@ResponseBody
	public String userCodeExit(@RequestParam String userCode) {
		logger.debug("userCodeExit userCode===============" + userCode);
		User user = userService.selectUserCodeExist(userCode);
		HashMap<String, String> resMap = new HashMap<String, String>();

		if (null != user) {
			// 用户名已存在
			resMap.put("userCode", "exist");
		} else {
			// 用户名可用
			resMap.put("userCode", "notexist");
		}
		return JSONArray.toJSONString(resMap);

	}

	/**
	 * 查看单个用户
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/userview.html/{id}")
	public String viewUser(@PathVariable String id, Model model) {
		User user = userService.getUserById(id);
		model.addAttribute("user", user);
		return "userview.jsp";
	}

	/**
	 * 删除用户
	 * @param id 传值进去
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/deluserById")
	@ResponseBody
	public Object delByUser(@RequestParam String id) {
		logger.debug("delByUser ===============id " + id);
		HashMap<String, String> resultMap = new HashMap<String, String>();
		Integer _id = Integer.valueOf(id);
		if (_id <= 0) {
			resultMap.put("delResult", "notexist");
		} else {
			if (userService.deleteUserById(_id)) {
				resultMap.put("delResult", "true");
			} else {
				resultMap.put("delResult", "false");
			}
		}
		return JSONArray.toJSONString(resultMap);

	}

	/**
	 * 查看视图
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/viewAiax"/* ,produces= "application/json;charset=utf-8" */)
	@ResponseBody
	public Object viewAjax(@RequestParam String id) {
		logger.debug("viewAjax id==============================" + id);
		User user = userService.getUserById(id);
		return user;
	}

}
